package com.bdq.content.application.service.impl;

import cn.hutool.core.convert.Convert;
import com.bdq.common.entity.UserContext;
import com.bdq.common.enums.ActivityTypeEnum;
import com.bdq.common.feign.interaction.param.InteractionNumInitParam;
import com.bdq.common.feign.interaction.param.VoteInitParam;
import com.bdq.common.utils.UserContextUtil;
import com.bdq.content.application.model.cmd.ContentPostCmd;
import com.bdq.content.application.service.ContentCmdService;
import com.bdq.content.application.service.MyFeignClient;
import com.bdq.content.domain.model.agg.ContentAgg;
import com.bdq.content.domain.model.dto.req.ContentPostLocationReqDTO;
import com.bdq.content.domain.model.dto.req.ContentPostReqDTO;
import com.bdq.content.domain.model.value.ContentVoteOptionValue;
import com.bdq.content.domain.service.ContentDomainService;
import com.bdq.common.config.common.TokenInterceptor;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.stream.Collectors;

/**
 * @author malei
 * @date 2024-05-10 16:21
 */
@Service
public class ContentCmdServiceImpl implements ContentCmdService {

    @Resource
    private ContentDomainService contentDomainService;

    @Resource
    private MyFeignClient myFeignClient;

    @Override
    public Boolean postContent(ContentPostCmd cmd) {
        // 1 获取用户信息
        UserContext userContext = UserContextUtil.getLoginUserContext(TokenInterceptor.getToken());

        // 2 发布
        ContentPostReqDTO reqDTO = Convert.convert(ContentPostReqDTO.class, cmd);
        reqDTO.setUserId(userContext.getId());
        reqDTO.setRole(userContext.getRole());
        reqDTO.setLocation(Convert.convert(ContentPostLocationReqDTO.class, userContext.getUserLocation()));
        ContentAgg contentAgg = contentDomainService.postContent(reqDTO);

        // 3 初始化交互数
        InteractionNumInitParam interactionNumInitParam = new InteractionNumInitParam();
        interactionNumInitParam.setContentId(contentAgg.getId());
        myFeignClient.interactionNumInit(interactionNumInitParam);

        // 4 初始化投票数
        if (ActivityTypeEnum.VOTE.getCode() == contentAgg.getActivityType()) {
            VoteInitParam voteInitParam = new VoteInitParam();
            voteInitParam.setContentId(contentAgg.getId());
            voteInitParam.setContentVoteOptionIds(contentAgg.getContentVoteOptions().stream().map(ContentVoteOptionValue::getId).collect(Collectors.toList()));
            myFeignClient.voteInit(voteInitParam);
        }
        return true;
    }
}
